package com.zpark.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * @PackageName: com.zpark.config
 * @ClassName: RateLimiteConfig
 * @Description:
 * @author: RZS
 * @date: 2022/12/6  16:43
 */
@Configuration
public class RateLimiteConfig {

    /**
     * 接口限流：根据请求路径限流
     * 如果不使用@Primary注解，会报错
     * @return
     */
    @Bean
    @Primary
    public KeyResolver pathKeyResolver() {
        return exchange -> {
            System.err.println("接口限流: "+exchange.getRequest().getPath().toString());
            return Mono.just(exchange.getRequest().getPath().toString());
        };

        /*//写法2
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };*/
    }

    /**
     * 根据请求IP限流
     * @return
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> {
            System.err.println("根据请求IP限流: "+exchange.getRequest().getRemoteAddress().getHostName());
            return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
        };
    }

    /**
     * 根据请求参数中的userId进行限流
     * 请求地址写法：http://localhost:8801/rate/123?userId=lisi
     * @return
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange ->{
            System.err.println("根据请求参数中的userId进行限流: "+exchange.getRequest().getQueryParams().getFirst("userId"));
            return Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
        };
    }
}
